<template>
    <div class="header-page-box">
        <slot></slot>
        <div class="left-box">
            <svg class="back-icon" @click="backPage" v-if="showBack">
                <use xlink:href="#keowledge-fanhuishangyiji"></use>
            </svg>
            <div class="line" v-if="showBack"></div>
            <div class="name-input-box" :class="[editName && 'name-input-box-active']">
                <div class="doc-name" @dblclick="changeEditStatus" v-if="!editName">{{ docName }}</div>
                <svg class="doc-edit-icon" @click="changeEditStatus" v-if="!editName">
                    <use xlink:href="#keowledge-bianji"></use>
                </svg>
                <el-input v-if="editName" ref="editNameRef" v-model="docName" @blur="editNameBlur"></el-input>
            </div>
            <template v-if="showLately && saveTime">
                <svg class="lately-icon">
                    <use xlink:href="#keowledge-mobile-zuijin-weixuanzhong"></use>
                </svg>
                <div class="time-box">最近保存 {{ saveTime }}</div>
            </template>
        </div>
        <div class="right-box">
            <slot name="right"></slot>
            <div class="coor-box">
                <svg class="coor-icon">
                    <use xlink:href="#keowledge-ren"></use>
                </svg>
                <span class="coor-num">{{ coorList.length || 1 }}</span>
                <div class="coor-users-box">
                    <template v-for="(item, index) in coorList" :key="index">
                        <img :src="item.avatar ? item.avatar : userImg" v-if="index < 4"
                            :style="{ zIndex: coorList.length - index, marginLeft: `${index != 0 ? -4 : 0}px` }">
                    </template>
                </div>
                <div class="coor-more-box" v-if="coorList.length > 4">
                    +{{ coorList.length - 4 }}
                </div>
                <div class="coor-line"></div>
            </div>
            <template v-for="(item, index) in actionList">
                <svg class="action-icon" v-if="!item.hidden" :key="index" @click="changeActiveName(item)"
                    :ref="(el) => setRef(el, item)">
                    <use
                        v-bind:xlink:href="`#${(activeName == item.value || currentActive.value == item.value) ? item.iconActive : item.icon}`">
                    </use>
                </svg>
            </template>
            <el-button type="primary" @click="doAction('version')" :disabled="activeName == 'version'"
                v-if="showBack">{{ $t('message.buttons.saveVersion') }}</el-button>
            <el-button type="primary" @click="doAction('save')" :disabled="activeName == 'version'"
                :loading="saveLoading">{{ $t('message.buttons.saveHotKey') }}</el-button>
        </div>
        <!-- 标签的虚拟pop -->
        <el-popover ref="popoverRef" :virtual-ref="tagRef" trigger="click" virtual-triggering :visible="tagPopover"
            placement="bottom-start" popper-class="tag-popover-action">
            <div class="tag-body-box" v-click-outside="onClickOutside" v-loading="labelLoading">
                <div class="tag-input-box" :class="[searchTagFocus && 'tag-input-foucs']">
                    <el-input v-model="searchTag" @focus="inputFoucs" @blur="inputBlur"
                        :placeholder="$t('message.placeholder.searchLabel')"></el-input>
                </div>
                <el-scrollbar ref="tagListRef">
                    <div class="tag-lists">
                        <div v-for="(item, index) in fileterTagList" :key="index" class="tag-item"
                            @click="bindDocLabel(item)">
                            <div class="tag-colour" :style="{ 'background-color': item.colour }"></div>
                            <div></div>
                            <div class="tag-name-box" v-tooltip-auto-show>
                                <el-tooltip :content="item.tagName" effect="light">
                                    <div class="tag-name">{{ item.tagName }}</div>
                                </el-tooltip>
                            </div>
                            <svg class="check-icon">
                                <use
                                    v-bind:xlink:href="`#${item.isSelect ? 'keowledge-a-zu3739' : 'keowledge-a-juxing2862biankuang'}`">
                                </use>
                            </svg>
                        </div>
                        <div class="more-loading-box" v-if="labelPage.current != 1 && moreLoading">
                            <img class="refresh-img" src="../../assets/common/loading-page.gif">
                        </div>
                    </div>
                </el-scrollbar>
                <jvs-empty v-if="fileterTagList.length == 0" text="" size="160px" style="margin-top:20px;"></jvs-empty>
            </div>
        </el-popover>
    </div>
</template>

<script setup lang="ts">
import {
    ref,
    watch,
    onMounted,
    nextTick,
    computed,
    onBeforeUnmount,
    getCurrentInstance
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { changeFileName } from '@/api/knowledge'
import { useRouter } from "vue-router"
// import { getSessionStore } from '@/utils/store'
import userImg from "@/assets/common/user.png";
import { ClickOutside as vClickOutside } from 'element-plus'
import { getTagAlls, editDocTag } from '@/api/tag'
import useKnowledgeStore from '@/store/knowledge'
import * as O from '@/utils/uniqueId'
import { useHookI18n } from '@/hooks/i18n'
const { $t } = useHookI18n()
const knowStore = useKnowledgeStore()
const router = useRouter();
const instance: any = getCurrentInstance() as ComponentInternalInstance
const proxy: any = instance.proxy as any
const emit = defineEmits(["handleClick", "update:docInfo", 'close', 'otherAction', 'changeEditStatus'])
const props = defineProps({
    showWrit: {
        type: Boolean,
        default: false
    },
    showBack: {
        type: Boolean,
        default: true
    },
    activeName: {
        type: String,
        default: ''
    },
    showLately: {
        type: Boolean,
        default: false
    },
    docInfo: {
        type: Object,
        default() {
            return {}
        }
    },
    coorList: {
        type: Array,
        default: []
    },
    saveTime: {
        type: String
    },
    knowledgeType: {
        type: Number
    }
})
const editName = ref(false)
const editNameRef = ref()
const actionList = ref<any[]>([
    {
        label: '移动',
        value: 'move',
        icon: "keowledge-yidong",
        iconActive: 'keowledge-yidong-xuanzhong',
    },
    {
        label: '标签',
        value: 'tag',
        icon: "keowledge-biaoqianguanli",
        ref: 'tagRef',
        iconActive: 'keowledge-a-biaoqianguanli1',
    },
    {
        label: '写作',
        value: 'writ',
        icon: "keowledge-xiezuo",
        iconActive: 'keowledge-xiezuo-xuanzhong',
    },
    {
        label: '版本',
        value: 'version',
        icon: "keowledge-banben",
        iconActive: 'keowledge-banben-xuanzhong',
    }
])
const docName = ref('')
const tagRef = ref()
const searchTag = ref('')
const searchTagFocus = ref(false)
const tagPopover = ref(false)
const moreButtonRef = ref<any>({})
const currentActive = ref({})
const labelList = ref<any[]>([])
const labelPage = ref({
    size: 20,
    current: 1,
    total: 0
})
const labelLoading = ref(false)
const moreLoading = ref(false)
const tagListRef = ref()
const tagScrollTop = ref(0)
const saveLoading = ref(false)
const fileterTagList = computed(() => {
    return labelList.value.filter((item: any) => { return item.tagName.indexOf(searchTag.value) != -1 })
})
watch(() => props.docInfo, (newV) => {
    docName.value = newV.name
})
watch(() => props.showWrit, (newV) => {
    actionList.value[2].hidden = newV
})
watch(() => props.showBack, (newV) => {
    actionList.value[0].hidden = !newV
    actionList.value[1].hidden = !newV
    actionList.value[3].hidden = !newV
})
watch(() => editName.value, (newV) => {
    emit('changeEditStatus', newV)
})
onMounted(() => {
    docName.value = props.docInfo.name
    actionList.value[2].hidden = props.showWrit
    actionList.value[0].hidden = !props.showBack
    actionList.value[1].hidden = !props.showBack
    actionList.value[3].hidden = !props.showBack
    tagListRef.value.wrapRef.addEventListener("scroll", (e: { target: { scrollTop: any; scrollHeight: any; clientHeight: any; }; }) => {
        const scrollTop = e.target.scrollTop
        const scrollHeight = e.target.scrollHeight
        const clientHeight = e.target.clientHeight
        if (
            scrollTop > scrollHeight - clientHeight - 10 &&
            scrollTop > tagScrollTop.value &&
            !moreLoading.value && labelPage.value.current < Math.ceil(labelPage.value.total / labelPage.value.size)
        ) {
            labelPage.value.current++
            getLabel()
        }
        tagScrollTop.value = scrollTop
    })
    proxy.$eventBus.$on('changeSaveLoading', changeSvaeLoading)
})
onBeforeUnmount(() => {
    proxy.$eventBus.$off('changeSaveLoading', changeSvaeLoading)
})
function changeSvaeLoading(val: boolean) {
    saveLoading.value = val
}
function setRef(el: any, data: { value: string | number; }) {
    if (el) {
        moreButtonRef.value[data.value] = el
    }
}
function changeActiveName(item: { value?: any; }) {
    // currentOpen.value = item
    if (item.value == 'tag') {
        currentActive.value = item
        tagRef.value = moreButtonRef.value[item.value]
        tagPopover.value = true
        labelLoading.value = true
        getLabel()
    } else {
        emit('handleClick', item)
    }
}
function doAction(item: any) {
    emit('otherAction', item)
}
function changeEditStatus() {
    if (!props.showBack) return
    editName.value = true
    nextTick(() => {
        editNameRef.value.focus()
    })
}
function editNameBlur() {
    if (props.docInfo.name != docName.value && docName.value) {
        changeFileName({
            name: docName.value,
            id: props.docInfo.id
        }).then(res => {
            if (res.data.code == 0) {
                proxy.$onePrompt.$oneNotify({
                    title: "提示",
                    message: "修改文件名成功",
                    type: 'success',
                    position: 'bottom-right'
                })
                emit("update:docInfo", {
                    ...props.docInfo,
                    name: docName.value
                })
                if (typeof BroadcastChannel !== 'undefined') {
                    const knowledgeBroad = new BroadcastChannel('knowledgeMessage')
                    knowledgeBroad.postMessage({
                        type: "changeFileName",
                        data: {
                            id: props.docInfo.id,
                            key: 'name',
                            changeVal: docName.value
                        }
                    })
                }
                editName.value = false
            }
        })
    } else {
        docName.value = props.docInfo.name
        editName.value = false
    }
}
interface backData {
    breadPath: string[],
    dcLibrary: any,
    docId: string,
    enterFolderId: string,
    fromPage: string,
    knowId: string
}
function backPage() {
    let backUrl: {
        data: backData,
        num: number
    }
    const type = props.knowledgeType == 0 ? 'all' : props.knowledgeType == 1 ? 'my' : ''
    backUrl = knowStore.backPageList[O.uniqueId(type + '-' + props.docInfo.knowledgeId + '-' + props.docInfo.id)]
    if (!backUrl) {
        router.push('/knowledge/all')
    } else {
        const uniId = O.uniqueId(type + '-' + props.docInfo.knowledgeId)
        knowStore.setDcLibrary(backUrl.data.dcLibrary, uniId)
        knowStore.setEnterFolderId(backUrl.data.enterFolderId, uniId)
        knowStore.setBreadPath(backUrl.data.breadPath, uniId)
        if (backUrl.num <= 0) {
            knowStore.delBackPage(uniId)
        } else {
            backUrl.num--
            knowStore.changeBackPage(backUrl, uniId)
        }
        if (type == '' || typeof type == 'undefined') {
            router.push({
                path: backUrl.data.fromPage
            })
        } else {
            router.push({
                path: `/knowledge/${backUrl.data.fromPage}/${backUrl.data.knowId}`
            })
        }
    }
}
function onClickOutside() {
    labelList.value = []
    currentActive.value = {}
    tagRef.value = null
    tagPopover.value = false
    tagScrollTop.value = 0
    labelPage.value = {
        size: 20,
        current: 1,
        total: 0
    }
}
function getLabel() {
    moreLoading.value = true
    getTagAlls({
        dcId: props.docInfo.id,
        size: labelPage.value.size,
        current: labelPage.value.current
    }).then(res => {
        if (res.data.code == 0) {
            labelPage.value.total = res.data.data.total
            labelList.value.push(...res.data.data.records)
            labelLoading.value = false
            moreLoading.value = false
        }
    })
}
function inputFoucs() {
    searchTagFocus.value = true
}
function inputBlur() {
    searchTagFocus.value = false
}
function bindDocLabel(item: { isSelect: boolean; }) {
    item.isSelect = !item.isSelect
    editDocTag({
        ...item,
        dcId: props.docInfo.id
    }).then(res => {
        if (res.data.code == 0) {
            let msg = "绑定标签成功"
            if (!item.isSelect) {
                msg = "解绑标签成功"
            }
            proxy.$onePrompt.$oneNotify({
                title: msg,
                type: "success",
                position: "bottom-right",
            });
        }
    })
}
defineExpose({
})
</script>
<style lang="scss" scoped>
.header-page-box {
    height: 48px;
    min-height: 48px;
    background-color: #fff;
    border-bottom: 1px solid #eeeff0;
    box-sizing: border-box;
    padding: 0px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;

    .left-box {
        display: flex;
        align-items: center;
        height: 34px;

        .back-icon {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .line {
            width: 1px;
            height: 16px;
            background: #C2C5CF;
            margin: 0px 16px;
        }

        .lately-icon {
            width: 14px;
            height: 14px;
            margin-right: 6px;
        }

        .time-box {
            font-size: 14px;
            color: #6F7588;
        }

        .name-input-box {
            border: 1px solid transparent;
            box-sizing: border-box;
            border-radius: 4px;
            overflow: hidden;
            margin-right: 8px;
            display: flex;
            align-items: center;

            .doc-name {
                color: #363B4C;
                font-size: 16px;
                cursor: pointer;
            }

            .doc-edit-icon {
                width: 16px;
                height: 16px;
                cursor: pointer;
                margin-left: 8px;
            }
        }

        .name-input-box-active {
            background: #F5F6F7;
            border-color: #1E6FFF;

            ::v-deep(.el-input__wrapper) {
                box-shadow: none !important;
                background: transparent !important;
            }
        }
    }

    .right-box {
        display: flex;
        align-items: center;
        position: relative;

        .action-icon {
            margin-right: 16px;
            width: 16px;
            height: 16px;
            cursor: pointer;
            outline: none !important;
        }

        .coor-box {
            display: flex;
            align-items: center;

            .coor-icon {
                width: 16px;
                height: 16px;
                margin-right: 6px;
            }

            .coor-num {
                font-size: 14px;
                color: #363B4C;
                margin-right: 12px;
            }

            .coor-users-box {
                display: flex;
                align-items: center;
                position: relative;

                img {
                    background-color: #fff;
                    position: relative;
                    width: 24px;
                    height: 24px;
                    border-radius: 6px 6px 6px 6px;
                    opacity: 1;
                    overflow: hidden;
                    border: 2px solid #FFFFFF;
                }
            }

            .coor-more-box {
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 14px;
                width: 24px;
                height: 24px;
                background: #EDF4FF;
                border-radius: 6px 6px 6px 6px;
                opacity: 1;
                border: 2px solid #1E6FFF;
                color: #1E6FFF;
                margin-left: -4px;
                cursor: pointer;
            }

            .coor-line {
                margin: 0px 16px;
                width: 1px;
                height: 16px;
                background: #D8D8D8;
            }
        }
    }
}
</style>